/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.admin.api.feign.RemoteFileService;
import com.ykht.proj.common.core.constant.CommonConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.RecommendStatusEnum;
import com.ykht.proj.coupon.entity.FxCmsInfo;
import com.ykht.proj.coupon.service.FxCmsInfoService;
import com.ykht.proj.coupon.vo.FxCmsInfoCount;
import com.ykht.proj.coupon.vo.FxCmsInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * cms资讯表
 *
 * @author proj code generator
 * @date 2021-02-01 16:22:52
 */
@RestController
@AllArgsConstructor
@RequestMapping("/fxcmsinfo")
@Api(value = "fxcmsinfo", tags = "cms资讯表管理")
@Slf4j
public class FxCmsInfoController {

	private final FxCmsInfoService fxCmsInfoService;
	private final RemoteFileService remoteFileService;

	/**
	 * 分页查询
	 *
	 * @param page        分页对象
	 * @param fxCmsInfoVO cms资讯表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	public R getFxCmsInfoPage(Page page, FxCmsInfoVO fxCmsInfoVO) {
		return R.ok(fxCmsInfoService.queryByPage(page, fxCmsInfoVO));
	}

	/**
	 * 通过id查询cms资讯表（文章）
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询cms资讯表（文章）", notes = "通过id查询cms资讯表（文章）")
	@GetMapping("/{id}")
	public R<FxCmsInfoVO> getById(@PathVariable("id") Long id) {
		log.info("通过id查询cms资讯表（文章）:{}", id);
		FxCmsInfoVO fxCmsInfoVO = fxCmsInfoService.getByIdFxCmsInfoVO(id);
		return R.ok(fxCmsInfoVO);
	}

	/**
	 * 新增cms资讯表
	 *
	 * @param fxCmsInfo cms资讯表
	 * @return R
	 */
	@ApiOperation(value = "新增cms资讯表", notes = "新增cms资讯表")
	@SysLog("新增cms资讯表")
	@PostMapping
	public R save(@RequestBody FxCmsInfoVO fxCmsInfoVO) {
		log.info("新增cms资讯表:{}", fxCmsInfoVO);
		if (null == fxCmsInfoVO || fxCmsInfoVO.getBrandList().size() == 0 && fxCmsInfoVO.getStatus() != 1) return R.failed("至少选择一个品牌");
		if ((null == fxCmsInfoVO || fxCmsInfoVO.getColumnIdList().size() == 0) && fxCmsInfoVO.getStatus() != 1) return R.failed("至少选择一个栏目");
		if (null != fxCmsInfoVO.getStick() && fxCmsInfoVO.getStick().equals(1)){
			fxCmsInfoVO.setStickTime(LocalDateTime.now());
		}
		if (fxCmsInfoVO.getInformationType().equals(1) && !StringUtils.isNotEmpty(fxCmsInfoVO.getPcCover())){
			fxCmsInfoVO.setPcCover(fxCmsInfoVO.getVideoAddress() + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto");
		}
		fxCmsInfoVO.setCreateUser(SecurityUtils.getUserId());
		fxCmsInfoVO.setCreateTime(LocalDateTime.now());
		fxCmsInfoVO.setUpdateTime(LocalDateTime.now());
		fxCmsInfoVO.setContent(fxCmsInfoVO.getContent() != null ? this.getImgStr(fxCmsInfoVO.getContent()) : fxCmsInfoVO.getContent());
		return fxCmsInfoService.saveBatchFxCmsInfo(fxCmsInfoVO);
	}

	// 获取富文本中的图片路径
	public String getImgStr(String htmlStr) {
		if (htmlStr == null) return htmlStr;
		String content = null;
		try {
			content = htmlStr;
			String innerUrl = "https://static.quhouse.com";
			String regEx_img = "<img\\s[^>]+>";
			Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
			Matcher m_image = p_image.matcher(content);
			String img = "";
			while (m_image.find()) {
				// 得到<img />数据
				img = m_image.group();
				// 匹配<img>中的src数据
				Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
				while (m.find()) {
					String urls = m.group(1);
					if (urls.contains(innerUrl)) {
						continue;
					}
					if (urls != null && urls.length() > 0) {
						InputStream inputStream = new ByteArrayInputStream(HttpUtil.downloadBytes(urls));
						MultipartFile file = new MockMultipartFile(System.currentTimeMillis() + ".jpg", System.currentTimeMillis() + ".jpg"
								, ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
						R<String> r = remoteFileService.upload4url(file);
						if (CommonConstants.SUCCESS == r.getCode()) {
							String arpath = r.getData();
							log.info("\n原图片{}\n,替换后图片{}", urls, arpath);
							content = content.replace(urls, arpath);
						}
					} else {
						content = content.replace(img, "");
					}
				}
			}
			log.info("原html{}", htmlStr);
			log.info("替换后{}", content);
			return content;
		} catch (IOException e) {
			e.printStackTrace();
			return htmlStr;
		}
	}


	/**
	 * 修改cms资讯表
	 *
	 * @param fxCmsInfoVO cms资讯表
	 * @return R
	 */
	@ApiOperation(value = "修改cms资讯表", notes = "修改cms资讯表")
	@SysLog("修改cms资讯表")
	@PutMapping
	public R updateFxCmsInfo(@RequestBody FxCmsInfoVO fxCmsInfoVO) {
		log.info("修改cms资讯表:{}", fxCmsInfoVO);
		if (null != fxCmsInfoVO.getInformationType() && fxCmsInfoVO.getInformationType().equals(1) && !StringUtils.isNotEmpty(fxCmsInfoVO.getPcCover())){
			fxCmsInfoVO.setPcCover(fxCmsInfoVO.getVideoAddress() + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto");
		}
		if (null != fxCmsInfoVO.getStatus() && fxCmsInfoVO.getStatus().equals(3) && null == fxCmsInfoVO.getPublishTime()){
			fxCmsInfoVO.setPublishTime(LocalDateTime.now());
		}
		fxCmsInfoVO.setUpdateUser(SecurityUtils.getUserId());
		fxCmsInfoVO.setUpdateTime(LocalDateTime.now());
		fxCmsInfoVO.setContent(fxCmsInfoVO.getContent() != null ? this.getImgStr(fxCmsInfoVO.getContent()) : fxCmsInfoVO.getContent());
		fxCmsInfoService.updateFxCmsInfo(fxCmsInfoVO);
		return R.ok();
	}

	/**
	 * 批量修改cms资讯 栏目
	 *
	 * @param fxCmsInfoVO cms资讯表
	 * @return R
	 */
	@ApiOperation(value = "批量修改cms资讯 栏目", notes = "批量修改cms资讯 栏目")
	@SysLog("批量修改cms资讯 栏目")
	@PostMapping("updateColumnId")
	public R updateColumnId(@RequestBody FxCmsInfoVO  fxCmsInfoVO) {
		log.info("批量修改cms资讯 栏目:{}", fxCmsInfoVO);
		fxCmsInfoService.updateColumnId(fxCmsInfoVO.getIdList(), fxCmsInfoVO.getColumnIdList());
		return R.ok();
	}

	@ApiOperation(value = "修改cms资讯表状态", notes = "修改cms资讯表状态")
	@SysLog("修改cms资讯表状态")
	@PutMapping("/updateStatus")
//    @PreAuthorize("@pms.hasPermission('coupon_fxcmsinfo_edit')" )
	public R updateStatus(String ids, Integer status) {
		Long userId = SecurityUtils.getUserId();
		fxCmsInfoService.updateStatus(ids, status, userId);
		return R.ok();
	}


	/**
	 * 通过id删除cms资讯表
	 *
	 * @param ids id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除cms资讯表", notes = "通过id删除cms资讯表")
	@SysLog("通过id删除cms资讯表")
	@GetMapping("/delIds")
	//@PreAuthorize("@pms.hasPermission('coupon_fxcmsinfo_del')" )
	public R removeById(String ids) {
		String[] split = ids.split(",");
		for (String s : split) {
			fxCmsInfoService.delById(Long.parseLong(s));
		}
		return R.ok();
	}

	@ApiOperation(value = "通过id删除cms资讯表", notes = "通过id删除cms资讯表")
	@SysLog("通过id删除cms资讯表")
	@DeleteMapping("/{id}")
//	@PreAuthorize("@pms.hasPermission('coupon_fxconfreward_del')" )
	public R removeById(@PathVariable Long id) {
		fxCmsInfoService.delById(id);
		return R.ok();
	}


	/**
	 * 计数查询
	 *
	 * @return
	 */
	@ApiOperation(value = "计数查询", notes = "计数查询")
	@GetMapping("/count")
	//@PreAuthorize("@pms.hasPermission('coupon_fxcmssource_view')" )
	public R getFxCmsInfoCount(FxCmsInfoVO fxCmsInfoVO) {
		FxCmsInfoCount count = fxCmsInfoService.queryCount(fxCmsInfoVO);
		return R.ok(count);
	}


	@ApiOperation(value = "修改cms资讯表（排序，置顶，虚拟阅读量）", notes = "修改cms资讯表（排序，置顶，虚拟阅读量）")
	@SysLog("修改cms资讯表（排序，置顶，虚拟阅读量）")
	@PostMapping("/updateStick")
	public R updateStick(@RequestBody FxCmsInfo fxCmsInfo) {
		log.info("修改cms资讯表（排序，置顶，虚拟阅读量）", fxCmsInfo);
		if (null != fxCmsInfo.getStick() && fxCmsInfo.getStick().equals(1)){
			fxCmsInfo.setStickTime(LocalDateTime.now());
		}
		fxCmsInfo.setUpdateUser(SecurityUtils.getUserId());
		fxCmsInfo.setUpdateTime(LocalDateTime.now());
		return R.ok(fxCmsInfoService.updateById(fxCmsInfo));
	}

	@ApiOperation(value = "添加cms资讯表（推荐值）", notes = "添加cms资讯表（推荐值）")
	@SysLog("添加cms资讯表（推荐值）")
	@PostMapping("/addRecommend")
	public R addRecommend(@RequestBody FxCmsInfo fxCmsInfo) {
		log.info("添加cms资讯表（推荐值）", fxCmsInfo);
		if (null != fxCmsInfo.getRecommendValue()){
			if (LocalDateTime.now().isBefore(fxCmsInfo.getRecommendStartTime())) {
				fxCmsInfo.setRecommendStatus(RecommendStatusEnum.TO_START.getValue());
			} else {
				fxCmsInfo.setRecommendStatus(RecommendStatusEnum.AT_WORK.getValue());
			}
		}
		fxCmsInfo.setUpdateUser(SecurityUtils.getUserId());
		fxCmsInfo.setUpdateTime(LocalDateTime.now());
		fxCmsInfoService.addRecommend(fxCmsInfo);
		return R.ok();
	}


}
